<template>
  <div class="finance-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-left">
        <h2>财务管理</h2>
      </div>
      <div class="header-right">
        <a-button type="primary" @click="handleWithdraw">
          <template #icon><icon-export /></template>
          申请提现
        </a-button>
      </div>
    </div>

    <!-- 账户概览 -->
    <a-row :gutter="16" class="overview-section">
      <a-col :span="8">
        <a-card class="overview-card" :bordered="false">
          <div class="card-content">
            <div class="card-title">
              <span>账户余额</span>
              <a-tooltip content="可提现金额">
                <icon-question-circle />
              </a-tooltip>
            </div>
            <div class="card-amount">¥{{ accountInfo.balance }}</div>
            <div class="card-actions">
              <a-button type="text" @click="handleWithdraw">
                提现
                <template #icon><icon-right /></template>
              </a-button>
            </div>
          </div>
        </a-card>
      </a-col>

      <a-col :span="8">
        <a-card class="overview-card" :bordered="false">
          <div class="card-content">
            <div class="card-title">
              <span>待结算</span>
              <a-tooltip content="订单完成后的待结算金额">
                <icon-question-circle />
              </a-tooltip>
            </div>
            <div class="card-amount">¥{{ accountInfo.pending }}</div>
            <div class="card-actions">
              <a-button type="text" @click="handleViewPending">
                查看明细
                <template #icon><icon-right /></template>
              </a-button>
            </div>
          </div>
        </a-card>
      </a-col>

      <a-col :span="8">
        <a-card class="overview-card" :bordered="false">
          <div class="card-content">
            <div class="card-title">
              <span>已结算</span>
              <a-tooltip content="本月已结算金额">
                <icon-question-circle />
              </a-tooltip>
            </div>
            <div class="card-amount">¥{{ accountInfo.settled }}</div>
            <div class="card-actions">
              <a-button type="text" @click="handleViewSettled">
                查看明细
                <template #icon><icon-right /></template>
              </a-button>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 收支明细 -->
    <a-card class="detail-card" :bordered="false">
      <template #title>
        <div class="card-title-wrapper">
          <span>收支明细</span>
          <a-radio-group v-model="detailType" type="button">
            <a-radio value="all">全部</a-radio>
            <a-radio value="income">收入</a-radio>
            <a-radio value="expense">支出</a-radio>
          </a-radio-group>
        </div>
      </template>

      <!-- 搜索表单 -->
      <a-form :model="searchForm" layout="inline" class="search-form">
        <a-form-item field="dateRange" label="时间范围">
          <a-range-picker v-model="searchForm.dateRange" style="width: 260px" />
        </a-form-item>
        <a-form-item field="type" label="交易类型">
          <a-select
            v-model="searchForm.type"
            placeholder="请选择交易类型"
            allow-clear
            style="width: 200px"
          >
            <a-option value="order">订单收入</a-option>
            <a-option value="refund">退款支出</a-option>
            <a-option value="withdraw">提现</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><icon-search /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><icon-refresh /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 明细表格 -->
      <a-table
        :data="detailList"
        :columns="columns"
        :pagination="pagination"
        @page-change="onPageChange"
        :sortable="true"
        @sorter-change="handleSorterChange"
      >
        <!-- 交易信息 -->
        <template #infoTitle="{ column }">
          <div class="column-title">
            {{ column.title }}
            <div class="sort-buttons">
              <IconUp
                :class="{
                  active:
                    sortKeys.field === 'createTime' &&
                    sortKeys.order === 'ascend',
                }"
                @click="handleSort('createTime', 'ascend')"
              />
              <IconDown
                :class="{
                  active:
                    sortKeys.field === 'createTime' &&
                    sortKeys.order === 'descend',
                }"
                @click="handleSort('createTime', 'descend')"
              />
            </div>
          </div>
        </template>

        <!-- 关联订单 -->
        <template #orderTitle="{ column }">
          <div class="column-title">
            {{ column.title }}
            <div class="sort-buttons">
              <IconUp
                :class="{
                  active:
                    sortKeys.field === 'order.orderNo' &&
                    sortKeys.order === 'ascend',
                }"
                @click="handleSort('order.orderNo', 'ascend')"
              />
              <IconDown
                :class="{
                  active:
                    sortKeys.field === 'order.orderNo' &&
                    sortKeys.order === 'descend',
                }"
                @click="handleSort('order.orderNo', 'descend')"
              />
            </div>
          </div>
        </template>

        <!-- 收支金额 -->
        <template #amountTitle="{ column }">
          <div class="column-title">
            {{ column.title }}
            <div class="sort-buttons">
              <IconUp
                :class="{
                  active:
                    sortKeys.field === 'amount' && sortKeys.order === 'ascend',
                }"
                @click="handleSort('amount', 'ascend')"
              />
              <IconDown
                :class="{
                  active:
                    sortKeys.field === 'amount' && sortKeys.order === 'descend',
                }"
                @click="handleSort('amount', 'descend')"
              />
            </div>
          </div>
        </template>

        <!-- 交易信息 -->
        <template #info="{ record }">
          <div class="transaction-info">
            <div class="transaction-type">{{ record.typeText }}</div>
            <div class="transaction-time">{{ record.createTime }}</div>
          </div>
        </template>

        <!-- 关联订单 -->
        <template #order="{ record }">
          <div v-if="record.order" class="order-info">
            <div class="order-no">{{ record.order.orderNo }}</div>
            <div class="order-amount">¥{{ record.order.amount }}</div>
          </div>
          <span v-else>-</span>
        </template>

        <!-- 收支金额 -->
        <template #amount="{ record }">
          <span
            class="amount"
            :class="record.type === 'income' ? 'income' : 'expense'"
          >
            {{ record.type === "income" ? "+" : "-" }}¥{{ record.amount }}
          </span>
        </template>

        <!-- 状态 -->
        <template #status="{ record }">
          <a-tag :color="getStatusColor(record.status)">
            {{ record.statusText }}
          </a-tag>
        </template>
      </a-table>
    </a-card>

    <!-- 提现弹窗 -->
    <a-modal
      v-model:visible="withdrawVisible"
      title="申请提现"
      @ok="handleWithdrawSubmit"
      @cancel="handleWithdrawCancel"
      :footer="false"
      width="600px"
    >
      <div class="withdraw-modal-content">
        <!-- 账户余额展示 -->
        <div class="balance-info">
          <div class="info-item">
            <span class="label">可提现余额</span>
            <span class="value">¥{{ accountInfo.balance }}</span>
          </div>
          <div class="info-item">
            <span class="label">待结算金额</span>
            <span class="value pending">¥{{ accountInfo.pending }}</span>
          </div>
        </div>

        <a-form
          ref="withdrawFormRef"
          :model="withdrawForm"
          layout="vertical"
          class="withdraw-form"
        >
          <!-- 提现金额 -->
          <a-form-item
            field="amount"
            label="提现金额"
            :rules="[
              { required: true, message: '请输入提现金额' },
              {
                validator: validateAmount,
                message: '提现金额必须大于0且不超过可提现余额',
              },
            ]"
          >
            <div class="amount-input-wrapper">
              <a-input-number
                v-model="withdrawForm.amount"
                :min="0"
                :max="accountInfo.balance"
                :precision="2"
                :step="100"
                placeholder="请输入提现金额"
                style="width: 100%"
              >
                <template #prefix>¥</template>
              </a-input-number>
              <a-button
                type="text"
                class="all-amount-btn"
                @click="withdrawForm.amount = accountInfo.balance"
              >
                全部提现
              </a-button>
            </div>
          </a-form-item>

          <!-- 提现账户 -->
          <a-form-item
            field="account"
            label="提现账户"
            :rules="[{ required: true, message: '请选择提现账户' }]"
          >
            <a-select
              v-model="withdrawForm.account"
              placeholder="请选择提现账户"
            >
              <template #prefix>
                <icon-bank />
              </template>
              <a-option
                v-for="account in withdrawAccounts"
                :key="account.id"
                :value="account.id"
              >
                <div class="account-option">
                  <span class="account-name">{{ account.name }}</span>
                  <span class="account-number">{{ account.account }}</span>
                </div>
              </a-option>
            </a-select>
            <div class="add-account-tip">
              <icon-plus />
              <a-link>添加提现账户</a-link>
            </div>
          </a-form-item>

          <!-- 验证码 -->
          <a-form-item
            field="verifyCode"
            label="验证码"
            :rules="[{ required: true, message: '请输入验证码' }]"
          >
            <div class="verify-code-wrapper">
              <div class="phone-info">
                <icon-mobile />
                <span class="phone-number">{{
                  maskPhoneNumber(userInfo.phone)
                }}</span>
                <a-link @click="handleChangePhone">更换</a-link>
              </div>
              <div class="verify-code-input">
                <a-input
                  v-model="withdrawForm.verifyCode"
                  placeholder="请输入验证码"
                  maxlength="6"
                >
                  <template #prefix>
                    <icon-safe />
                  </template>
                </a-input>
                <a-button
                  type="primary"
                  :disabled="codeTimer > 0"
                  @click="sendVerifyCode"
                >
                  {{ codeTimer > 0 ? `${codeTimer}s后重试` : "获取验证码" }}
                </a-button>
              </div>
            </div>
          </a-form-item>

          <!-- 提交按钮 -->
          <div class="form-actions">
            <a-button type="primary" long @click="handleWithdrawSubmit">
              确认提现
            </a-button>
          </div>
        </a-form>

        <!-- 提示信息 -->
        <div class="withdraw-tips">
          <div class="tips-header">
            <icon-info-circle />
            <span>温馨提示</span>
          </div>
          <div class="tips-content">
            <p>1. 提现金额必须大于0且不超过可提现余额</p>
            <p>2. 提现申请将在1-3个工作日内处理</p>
            <p>3. 请确保提现账户信息准确无误</p>
            <p>4. 如遇问题请联系客服：400-xxx-xxxx</p>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { Message } from "@arco-design/web-vue";
import {
  IconExport,
  IconRight,
  IconSearch,
  IconRefresh,
  IconQuestionCircle,
  IconUp,
  IconDown,
  IconBank,
  IconSafe,
  IconInfoCircle,
  IconPlus,
  IconMobile,
} from "@arco-design/web-vue/es/icon";

// 账户信息
const accountInfo = reactive({
  balance: 12345.67,
  pending: 5678.9,
  settled: 23456.78,
});

// 明细类型
const detailType = ref("all");

// 搜索表单
const searchForm = reactive({
  dateRange: [],
  type: null,
});

// 排序状态
const sortKeys = reactive({
  field: "",
  order: "",
});

// 表格列配置
const columns = [
  {
    title: "交易信息",
    dataIndex: "createTime",
    slotName: "info",
    titleSlot: "infoTitle",
    sortable: { sortDirections: ["ascend", "descend"] },
  },
  {
    title: "关联订单",
    dataIndex: "order.orderNo",
    slotName: "order",
    titleSlot: "orderTitle",
    sortable: { sortDirections: ["ascend", "descend"] },
  },
  {
    title: "收支金额",
    dataIndex: "amount",
    slotName: "amount",
    titleSlot: "amountTitle",
    sortable: { sortDirections: ["ascend", "descend"] },
  },
  {
    title: "状态",
    dataIndex: "status",
    slotName: "status",
  },
];

// 明细列表数据
const detailList = ref([
  {
    id: 1,
    type: "income",
    typeText: "订单收入",
    createTime: "2024-03-15 12:34:56",
    order: {
      orderNo: "SO2024031500001",
      amount: "299.00",
    },
    amount: "299.00",
    status: "success",
    statusText: "已完成",
  },
  {
    id: 2,
    type: "expense",
    typeText: "退款支出",
    createTime: "2024-03-14 15:30:00",
    order: {
      orderNo: "SO2024031400002",
      amount: "199.00",
    },
    amount: "-199.00",
    status: "success",
    statusText: "已完成",
  },
  {
    id: 3,
    type: "income",
    typeText: "订单收入",
    createTime: "2024-03-13 09:15:00",
    order: {
      orderNo: "SO2024031300003",
      amount: "599.00",
    },
    amount: "599.00",
    status: "pending",
    statusText: "待结算",
  },
  {
    id: 4,
    type: "expense",
    typeText: "提现",
    createTime: "2024-03-12 16:45:00",
    order: null,
    amount: "-1000.00",
    status: "pending",
    statusText: "处理中",
  },
]);

// 分页配置
const pagination = reactive({
  total: 100,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
});

// 提现账户列表
const withdrawAccounts = [
  {
    id: 1,
    name: "工商银行",
    account: "6222************1234",
  },
  {
    id: 2,
    name: "支付宝",
    account: "137****8888",
  },
];

// 提现弹窗
const withdrawVisible = ref(false);
const withdrawFormRef = ref(null);
const withdrawForm = reactive({
  amount: null,
  account: null,
  verifyCode: "",
});
const codeTimer = ref(0);

// 用户信息
const userInfo = reactive({
  phone: "13812345678", // 从用户信息接口获取
});

// 手机号脱敏处理
const maskPhoneNumber = (phone) => {
  if (!phone) return "";
  return phone.replace(/(\d{3})\d{4}(\d{4})/, "$1****$2");
};

// 验证提现金额
const validateAmount = (value) => {
  if (!value || value <= 0 || value > accountInfo.balance) {
    return false;
  }
  return true;
};

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    success: "green",
    pending: "orange",
    failed: "red",
  };
  return colorMap[status] || "default";
};

// 处理搜索
const handleSearch = () => {
  // TODO: 调用搜索API
  Message.success("搜索成功");
};

// 处理重置
const handleReset = () => {
  searchForm.dateRange = [];
  searchForm.type = null;
};

// 处理分页
const onPageChange = (page) => {
  pagination.current = page;
  // TODO: 加载对应页数据
};

// 查看待结算明细
const handleViewPending = () => {
  detailType.value = "all";
  searchForm.type = "pending";
  handleSearch();
};

// 查看已结算明细
const handleViewSettled = () => {
  detailType.value = "all";
  searchForm.type = "settled";
  handleSearch();
};

// 处理提现
const handleWithdraw = () => {
  withdrawForm.amount = null;
  withdrawForm.account = null;
  withdrawForm.verifyCode = "";
  withdrawVisible.value = true;
};

// 发送验证码
const sendVerifyCode = async () => {
  try {
    // TODO: 调用发送验证码API，传入用户手机号
    await new Promise((resolve) => setTimeout(resolve, 500));
    Message.success(`验证码已发送至 ${maskPhoneNumber(userInfo.phone)}`);
    codeTimer.value = 60;
    const timer = setInterval(() => {
      codeTimer.value--;
      if (codeTimer.value <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  } catch (error) {
    Message.error("验证码发送失败");
  }
};

// 更换手机号
const handleChangePhone = () => {
  Message.info("请前往个人中心-安全设置更换绑定手机号");
};

// 提交提现申请
const handleWithdrawSubmit = async () => {
  if (!withdrawFormRef.value) return;

  try {
    await withdrawFormRef.value.validate();
    // TODO: 调用提现API
    await new Promise((resolve) => setTimeout(resolve, 1000));
    Message.success("提现申请已提交");
    withdrawVisible.value = false;
  } catch (error) {
    console.error(error);
    Message.error("表单验证失败");
  }
};

// 取消提现
const handleWithdrawCancel = () => {
  withdrawFormRef.value?.resetFields();
  withdrawVisible.value = false;
};

// 处理表格排序变化
const handleSorterChange = (opt) => {
  if (!opt) {
    return;
  }

  const { field, direction } = opt;
  sortKeys.field = field;
  sortKeys.order = direction;
  handleSort(field, direction);
};

// 排序处理函数
const handleSort = (field, order) => {
  if (!field || !order) {
    return;
  }

  const sortedList = [...detailList.value];
  sortedList.sort((a, b) => {
    let compareA = field.includes(".")
      ? field.split(".").reduce((obj, key) => obj[key], a)
      : a[field];
    let compareB = field.includes(".")
      ? field.split(".").reduce((obj, key) => obj[key], b)
      : b[field];

    // 处理特殊字段
    if (field === "amount") {
      compareA = parseFloat(compareA.replace(/[^0-9.-]+/g, "")) || 0;
      compareB = parseFloat(compareB.replace(/[^0-9.-]+/g, "")) || 0;
    } else if (field === "createTime") {
      compareA = new Date(compareA).getTime();
      compareB = new Date(compareB).getTime();
    }

    if (order === "ascend") {
      return compareA > compareB ? 1 : -1;
    } else if (order === "descend") {
      return compareA < compareB ? 1 : -1;
    }
    return 0;
  });

  detailList.value = sortedList;
  Message.success(`${order === "ascend" ? "升序" : "降序"}排序成功`);
};
</script>

<style lang="scss" scoped>
.finance-page {
  .page-header {
    @apply flex items-center justify-between mb-6;

    h2 {
      @apply text-xl font-medium;
    }
  }

  .overview-section {
    @apply mb-6;

    .overview-card {
      @apply bg-white rounded-lg transition-shadow hover:shadow-md;

      .card-content {
        .card-title {
          @apply flex items-center text-gray-600 mb-2;

          .icon-question-circle {
            @apply ml-1 text-gray-400 cursor-help;
          }
        }

        .card-amount {
          @apply text-2xl font-medium;
        }

        .card-actions {
          @apply mt-4;
        }
      }
    }
  }

  .detail-card {
    .card-title-wrapper {
      @apply flex items-center justify-between;
    }

    .search-form {
      @apply mb-4;
    }

    .transaction-info {
      .transaction-type {
        @apply font-medium mb-1;
      }

      .transaction-time {
        @apply text-sm text-gray-500;
      }
    }

    .order-info {
      .order-no {
        @apply text-sm mb-1;
      }

      .order-amount {
        @apply text-sm text-gray-500;
      }
    }

    .amount {
      @apply font-medium;

      &.income {
        @apply text-success-600;
      }

      &.expense {
        @apply text-danger-600;
      }
    }

    .column-title {
      display: flex;
      align-items: center;
      gap: 8px;

      .sort-buttons {
        display: inline-flex;
        flex-direction: column;
        gap: 2px;
        margin-left: 4px;

        :deep(.arco-icon) {
          font-size: 12px;
          color: var(--color-text-3);
          cursor: pointer;
          line-height: 1;
          padding: 2px;

          &:hover,
          &.active {
            color: rgb(var(--primary-6));
          }
        }
      }
    }
  }

  .verify-code-input {
    @apply flex gap-2;

    .arco-input {
      @apply flex-1;
    }

    .arco-btn {
      @apply w-32;
    }
  }

  .withdraw-tips {
    @apply mt-4 p-4 bg-gray-50 rounded-lg text-sm text-gray-600 space-y-1;
  }
}

// 提现弹窗样式
.withdraw-modal-content {
  .balance-info {
    @apply flex justify-between p-4 mb-6 bg-gray-50 rounded-lg;

    .info-item {
      @apply flex flex-col;

      .label {
        @apply text-sm text-gray-500 mb-1;
      }

      .value {
        @apply text-xl font-medium text-primary-600;

        &.pending {
          @apply text-orange-500;
        }
      }
    }
  }

  .withdraw-form {
    @apply mb-6;

    .amount-input-wrapper {
      @apply relative;

      .all-amount-btn {
        @apply absolute right-0 top-1/2 -translate-y-1/2 text-primary-600 hover:text-primary-500;
      }
    }

    .account-option {
      @apply flex items-center justify-between;

      .account-name {
        @apply font-medium;
      }

      .account-number {
        @apply text-gray-500;
      }
    }

    .add-account-tip {
      @apply flex items-center gap-1 mt-2 text-sm text-gray-500;
    }

    .verify-code-wrapper {
      @apply space-y-3;

      .phone-info {
        @apply flex items-center gap-2 text-sm text-gray-600;

        .phone-number {
          @apply font-medium;
        }
      }

      .verify-code-input {
        @apply flex gap-4;

        .arco-input-wrapper {
          @apply flex-1;
        }

        .arco-btn {
          @apply w-32;
        }
      }
    }

    .form-actions {
      @apply mt-8;
    }
  }

  .withdraw-tips {
    @apply p-4 bg-gray-50 rounded-lg;

    .tips-header {
      @apply flex items-center gap-2 mb-3 text-gray-700 font-medium;

      .icon-info-circle {
        @apply text-primary-600;
      }
    }

    .tips-content {
      @apply text-sm text-gray-600 space-y-2;
    }
  }
}
</style>
